<?php
/*
 *      nwdataset.php
 *
 *      Copyright 2010 Rakitin Vitaliy <virak@ukr.net>
 *
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */
 
//namespace database;
require_once("./classes/DB/DB.php");
require_once("./classes/GUI/nwmsg.php");

class nwdataset {

	private $uuid;
	public $orderby;
	public $direction;
	public $limitnum;
	public $offsetnum;
	private $select;
	private $isedit = false;
	private $isinsert = false;
	private $doinsert = true;
	private $doedit = false;
	private $dodelete = false;
	private $clients = array();
	private $action;
	private $buffer = array();

	function __construct($uuid) {
		$this->uuid = $uuid;
		$this->orderby = $this->getprimary();
		$this->direction = "ASC";
		$this->limitnum = 20;
		$this->offsetnum = 0;
		$this->action = "";
		$_SESSION[$uuid] = &$this;
	}

	function registerme($uuid) {
		$this->clients[$uuid] = get_class($_SESSION[$uuid]);
	}

	function updateclients() {
		foreach ($this->clients as $client=>$value) {
			$_SESSION[$client]->update();
		}
	}

	function getdata() {
		
		$sql = "SELECT * FROM $this->uuid ORDER BY $this->orderby $this->direction LIMIT $this->limitnum OFFSET $this->offsetnum;";
		//new nwmsg($sql);
		return DB::select($sql);
	}
	
	function genheader() {
		$header = $this->getheader();
		$str = "";
		foreach ($header as $head) {
			if ($head["type"] == "link") {
				$link = $this->getlink($head["id"]);
				$str .= "(SELECT ".$link['displayfield']." FROM ".$link['object']." WHERE ".$link['keyfield']." = ".$head['id'].") AS ".$head['id'];
			} else {
				$str .= $head["id"];
			}
			$str .= ",";
		}
		return substr_replace($str, "", -1, 1);
	}
	
	function getlink($id) {
		$sql = "SELECT * FROM links WHERE id = '$id';";
		$result = DB::select($sql);
		return $result[0];
	}

	function getrow($row) {
		$sql = "SELECT * FROM $this->uuid WHERE ".$this->getprimary()." = '$row';";
		$result = DB::select($sql);
		return $result[0];
	}

	function getfieldbyid($id) {
		return $this->buffer[$id];
	}

	function setfieldbyid($id, $value) {
		if (!($this->isedit || $this->isinsert)) {
			//if (!$this->edit()) {return false;}
			return false;
		}
		
		$this->buffer[$id] = $value;
		//new nwmsg(print_r($this->buffer, true));
		return true;
	}

	function getheader() {
		$sql = "SELECT * FROM fields WHERE owner = '$this->uuid';";
		$result = DB::select($sql);
		//if ($result["type"] == "link") {
		//	$sql = "SELECT * FROM links WHERE owner = '$this->uuid';";
		//}
		return $result;
	}

	function getprimary() {
		//$sql = "SELECT id FROM fields WHERE (owner = '$this->uuid') AND (isprimary = true);";
		//$result = DB::select($sql);
		//return $result[0]["id"];
		return "id";
	}

	function getuuidfieldbyname($name) {
		$sql = "SELECT id FROM fields WHERE (owner = '$this->uuid') AND (name = '$name');";
		$result = DB::select($sql);
		return $result[0]["id"];
	}

	function row_is_lock($id) {
		$sql = "SELECT * FROM is_edit_row WHERE (table_id = '$this->uuid') AND (row_id = '$id');";
		$result = DB::select($sql);
		if (count($result) == 0) {return false;}
		return true;
	}

	function lock_row($id) {
		$time = date('Y-m-d H:i:s');
		$user_id = "uuid".session_id();
		$sql = "INSERT INTO is_edit_row VALUES ('$this->uuid','$this->select','$user_id', '$time');";
		return DB::query($sql);
	}

	function unlock_row() {
		$user_id = "uuid".session_id();
		$sql = "DELETE FROM is_edit_row WHERE (table_id = '$this->uuid') AND (row_id = '$this->select') AND (user_id = '$user_id');";
		if (DB::query($sql) == false) {
			return false;
		}
		return true;
	}

	function __get($name) {
		switch ($name) {
			case "select": {return $this->select; break;}
			case "uuid": {return $this->uuid;break;}
			case "selected": {break;}
			case "isedit": {return $this->isedit;break;}
			case "isinsert": {return $this->isinsert;break;}
			case "doinsert": {return $this->doinsert;break;}
			case "doedit": {return $this->doedit;break;}
			case "dodelete": {return $this->dodelete;break;}
		}
	}

	function __set($name, $value) {
		switch ($name) {
			case "select": {
				if (!((($this->isedit) || ($this->isinsert)) && ($this->select != $value))){
					//$this->cancel();
				
				$this->select = $value;
				$this->buffer = $this->getrow($this->select);
				$this->doedit = true;
				$this->updateclients();
				}
				break;
			}
		}
	}

	function post() {

		if ($this->isedit) {
			$primary = $this->getprimary();
			$this->action = "UPDATE $this->uuid SET";
			foreach ($this->buffer as $key=>$value) {
				if ($key != $primary) {
					$this->action .= " $key = '".addslashes($value)."'";
					$this->action .= ",";
				}
			}
			$this->action = substr_replace($this->action, "", -1, 1);
			$this->action .= " WHERE $primary = '$this->select';";
		}

		if ($this->isinsert) {
			$primary = $this->getprimary();
			$this->action = "INSERT INTO $this->uuid(";
			foreach ($this->buffer as $key=>$value) {
					$this->action .= " $key";
					$this->action .= ",";
			}
			$this->action = substr_replace($this->action, ")", -1, 1);
			
			$this->action .= " VALUES(";
			foreach ($this->buffer as $key=>$value) {
					$this->action .= " '".addslashes($value)."'";
					$this->action .= ",";
			}
			$this->action = substr_replace($this->action, ");", -1, 1);
		}

		if ($this->action != "") {
			DB::query($this->action);

		}

		if ($this->row_is_lock($this->select)) {
			if (!$this->unlock_row($this->select)) {
				new nwmsg("Не могу снять блокировку.");
				return false;
			}
		}

		$this->isedit = false;
		$this->isinsert = false;
		$this->updateclients();
		return true;
	}

	function insert() {
		$this->action = "";
		$uuid = genUUID();
		$this->buffer = array();
		$this->buffer[$this->getprimary()] = $uuid;
		$this->isinsert = true;
		$this->updateclients();
		return true;
	}

	function edit() {
		if ($this->select == "") {
			new nwmsg("Не выбрана ни одна строка.");
			return false;
		}
		if ($this->row_is_lock($this->select)) {
			//new nwmsg("Строка редактируется.");
			return false;
		}
		if (!$this->lock_row($this->select)) {
			new nwmsg("Не могу установить блокировку.");
			return false;
		}
		$this->isedit = true;
		$this->updateclients();
		return true;
	}

	function delete() {

		if ($this->select == "") {
			new nwmsg("Не выбрана ни одна строка.");
			return false;
		}
		if ($this->row_is_lock($this->select) != false) {
			new nwmsg("Строка редактируется.");
			return false;
		}
		if (!$this->lock_row($this->select)) {
			new nwmsg("Не могу установить блокировку.");
			return false;
		}
		$primary = $this->getprimary();
		$this->action = "DELETE FROM $this->uuid WHERE $primary = '$this->select';";
		return true;

	}

	function cancel() {
		if ($this->row_is_lock($this->select)) {
			if (!$this->unlock_row($this->select)) {
				new nwmsg("Не могу снять блокировку.");
				return false;
			}
		}
		$this->action = "";
		$this->isedit = false;
		$this->isinsert = false;
		$this->buffer = $this->getrow($this->select);
		$this->updateclients();
		return true;
	}
}
?>
